package com.lb.shopguide.http;

import com.lb.shopguide.BuildConfig;
import com.lb.shopguide.GuideApplication;
import com.lb.shopguide.http.configuration.ApiConfiguration;
import com.lb.shopguide.http.interceptor.ParamInterceptor;
import com.lb.shopguide.http.service.BossService;
import com.lb.shopguide.http.service.GuideService;
import com.netease.nim.uikit.common.util.sys.NetworkUtil;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.internal.cache.CacheInterceptor;
import okhttp3.internal.http.RetryAndFollowUpInterceptor;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * @author baronzhang (baron[dot]zhanglei[at]gmail[dot]com)
 * 16/2/25
 */
public final class ApiClient {

    public static BossService bossService;
    public static GuideService guideService;
//    public static EnvironmentCloudWeatherService environmentCloudWeatherService;

    public static ApiConfiguration configuration;

    public static void init(ApiConfiguration apiConfiguration) {

        configuration = apiConfiguration;
        String apiHost = ApiConstants.HOST_FORMAL_MOBILE_SERVER;
        switch (configuration.getDataSourceType()) {
            case ApiConstants.DATA_DEVELOP:
                apiHost = ApiConstants.HOST_DEVELOP_MOBILE_SERVER;
                break;
            case ApiConstants.DATA_BETA:
                apiHost = ApiConstants.HOST_BETA_MOBILE_SERVER;
                break;
            case ApiConstants.DATA_FORMAL:
                apiHost = ApiConstants.HOST_FORMAL_MOBILE_SERVER;
                break;
        }
        //service初始化
        bossService = initService(apiHost, BossService.class);
        guideService = initService(apiHost, GuideService.class);
    }

    private static <T> T initService(String baseUrl, Class<T> clazz) {
        Cache cache = new Cache(GuideApplication.getAppContext().getCacheDir(), 10 * 1024 * 1024);
        OkHttpClient.Builder builder = new OkHttpClient().newBuilder();
        if (BuildConfig.DEBUG) {
            HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
            httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            builder.addInterceptor(httpLoggingInterceptor);
        }
        builder.addNetworkInterceptor(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request request = chain.request();
                Response originalResponse = chain.proceed(request);
                int maxAge = 0; // 在线缓存,单位:秒
                return originalResponse.newBuilder().removeHeader("Pragma")// 清除头信息，因为服务器如果不支持，会返回一些干扰信息，不清除下面无法生效
                        .removeHeader("Cache-Control").header("Cache-Control", "public, max-age=" + maxAge).build();
            }
        });
        builder.addInterceptor(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request request = chain.request();
                if (!NetworkUtil.isNetAvailable(GuideApplication.getAppContext())) {
                    int maxStale = 7 * 24 * 60 * 60; // 离线时缓存保存1周
                    CacheControl tempCacheControl = new CacheControl.Builder().onlyIfCached().maxStale(maxStale, TimeUnit.SECONDS).build();
                    request = request.newBuilder().cacheControl(tempCacheControl).build();
                }
                return chain.proceed(request);
            }
        }).cache(cache);

        builder.retryOnConnectionFailure(true).connectTimeout(15, TimeUnit.SECONDS).readTimeout(20, TimeUnit.SECONDS).
                writeTimeout(20, TimeUnit.SECONDS).addInterceptor(new ParamInterceptor());
        OkHttpClient client = builder.build();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())//rxjava 需要加上这一句
                .client(client)
                .build();

        return retrofit.create(clazz);
    }

}

